package com.example.springbootdemo.kafka;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * kafka消息发送者
 */
@Slf4j
@Component
public class KafkaSender {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    /**
     *  发送文字消息
     * @param message
     * @return
     */
    public String sendStr(String message){
        log.info("kafka发送消息:" + message);
        kafkaTemplate.send("chang-test",message).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                log.info("发送失败");
            }
            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                log.info("发送成功");
            }
        });
        return message;
    }
    /**
     *  发送对象消息
     * @param obj
     * @return
     */
    public String sendObj(Object obj){
        String message = JSONUtil.parseObj(obj).toString();
        kafkaTemplate.send("chang-test",message);
        return message;
    }
}


